﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using ECGadmin.Common;
using ECGadmin.DAL;
using ECGadmin.WebUI.Attributes;
using ECGadmin.WebUI.CustomHelpers;
using ECGadmin.WebUI.Models;

namespace ECGadmin.WebUI.Controllers
{
    [AdminLoggedAuthorize]
    public class NewsController : Controller
    {
        //
        // GET: /News/

        public ActionResult Index(int page = 1)
        {
            var itemsPerPage = int.Parse(ConfigurationManager.AppSettings["DefaultItemsPerPage"]);
            var totalPage = 0;
            var totalRecord = 0;
            var model = NewsDb.GetAllNewsListAdmin_Pagging(page, itemsPerPage, ref totalPage, ref totalRecord) ?? new List<NewsListAdminDto>();
            ViewBag.PageInfo = new PageInfo { CurrentPage = page, PageSize = itemsPerPage, TotalPages = totalPage };
            ViewBag.TotalRecord = totalRecord;
            return View(model);
        }

        public ActionResult AddNews()
        {
            ViewBag.ParentList = FunctionHelper.GetMenuListThreeLevelNews() ?? new List<NewsCategoryDto>();
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddNews(NewsDto model, HttpPostedFileWrapper imageFile, string NameTag)
        {
            var error = string.Empty;
            var imagePath = string.Empty;
            var folderUpload = Server.MapPath(ConfigurationManager.AppSettings["NewsImagesPath"]);
            if (imageFile != null) imagePath = FunctionHelper.UploadImages(out error, folderUpload, imageFile);
            ViewBag.ParentList = FunctionHelper.GetMenuListThreeLevelNews() ?? new List<NewsCategoryDto>();
            model.Id = FunctionHelper.GenerateId();
            model.CreateDate = DateTime.Now;
            model.ImagePath = imagePath;
            NewsDb.Add(model);//add news
            //add Tag
            var listTag = NameTag.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (listTag.Length > 0)
            {
                //Them moi cac Tag neu trung thi bo
                foreach (var s in listTag)
                {
                    var modelTag = TagDb.GetTagName(s);

                    //neu tag chua co thi them moi 
                    if (modelTag == null || modelTag.Count < 0)
                    {
                        var tag = new TagDto { Id = FunctionHelper.GenerateId(), TagName = s, Type = "news" };
                        TagDb.Add(tag);

                        //them quan he Tag voi News
                        var listTagMap = TagDb.GetTagMap(model.Id, tag.Id);//kiem tra xem quan he nay da co truoc day chua
                        if (listTagMap == null || listTagMap.Count < 0) //neu chua them qh vao
                        {
                            var tagMap = new TagMapDto { MapId = model.Id, TagId = tag.Id };
                            TagMapDb.Add(tagMap);
                        }
                    }
                    else //neu tag co roi thi lay Id tag ve
                    {
                        var _Tag = modelTag[0];
                        //them quan he Tag voi News
                        var listTagMap = TagDb.GetTagMap(model.Id, _Tag.Id);
                        if (listTagMap == null || listTagMap.Count < 0)
                        {
                            var tagMap = new TagMapDto { MapId = model.Id, TagId = _Tag.Id };
                            TagMapDb.Add(tagMap);
                        }
                    }
                }
            }

            return RedirectToAction("Index", "News");
        }

        public ActionResult EditNews(string id)
        {
            ViewBag.ParentList = FunctionHelper.GetMenuListThreeLevelNews() ?? new List<NewsCategoryDto>();
            var model = NewsDb.GetById(id);
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditNews(NewsDto model, HttpPostedFileWrapper imageFile, string NameTag)
        {
            var error = string.Empty;
            var imagePath = string.Empty;
            var folderUpload = Server.MapPath(ConfigurationManager.AppSettings["NewsImagesPath"]);
            if (imageFile != null) imagePath = FunctionHelper.UploadImages(out error, folderUpload, imageFile);
            ViewBag.ParentList = FunctionHelper.GetMenuListThreeLevelNews() ?? new List<NewsCategoryDto>();
            if (imageFile != null)
                model.ImagePath = imagePath;
            
            NewsDb.Update(model);
            //Edit Tag
            var listTag = NameTag.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            //xoa toan bo quan he cua tin nay voi tag truoc do
            TagDb.DelTagMapByMapId(model.Id);
            if (listTag.Length > 0)
            {                
                //Them moi cac Tag neu trung thi bo
                foreach (var s in listTag)
                {
                    var modelTag = TagDb.GetTagName(s);

                    //neu tag chua co thi them moi 
                    if (modelTag == null || modelTag.Count < 0)
                    {
                        var tag = new TagDto { Id = FunctionHelper.GenerateId(), TagName = s, Type = "news" };
                        TagDb.Add(tag);

                        //them quan he Tag voi News
                        var listTagMap = TagDb.GetTagMap(model.Id, tag.Id); //kiem tra xem quan he nay da co truoc day chua
                        if (listTagMap == null || listTagMap.Count < 0) //neu chua thi them qh vao
                        {
                            var tagMap = new TagMapDto { MapId = model.Id, TagId = tag.Id };
                            TagMapDb.Add(tagMap);
                        }
                    }
                    else //neu tag co roi thi lay Id tag ve
                    {
                        var _Tag = modelTag[0];
                        //them quan he Tag voi News
                        var listTagMap = TagDb.GetTagMap(model.Id, _Tag.Id);
                        if (listTagMap == null || listTagMap.Count < 0)
                        {
                            var tagMap = new TagMapDto { MapId = model.Id, TagId = _Tag.Id };
                            TagMapDb.Add(tagMap);
                        }
                    }
                }
            }
            return RedirectToAction("Index", "News");
        }

        //hien thi cac tag theo record cu the
        public PartialViewResult ShowTag(string newsId)
        {
            var model = TagDb.GetTagNameByMapId(newsId) ?? new List<TagDto>();
            return PartialView(model);
        }

        public JsonResult DeleteNews(string id)
        {
            var result = NewsDb.Delete(id);
            var data = new { id, result };
            return Json(data, JsonRequestBehavior.AllowGet);
        }


    }
}
